package com.gitee.apanlh.util.dataformat.json;

import com.gitee.apanlh.util.base.IteratorUtils;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.check.CheckImport;
import com.gitee.apanlh.util.check.CheckLibrary;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.valid.ValidParam;

import java.util.Map;

/**
 * 	JSON构建器
 * 
 * 	@author Pan
 */
public class JsonBuilder {
	
	static {
		CheckImport.library(CheckLibrary.FASTJSON);
	}
	
	/** jsonMap对象 */
	private Map<String, Object> jsonMap;
	
	/**
	 * 	默认构造对象
	 * 
	 * 	@author Pan
	 */
	JsonBuilder() {
		super();
	}
	
	/**
	 * 	构造对象-自定义长度
	 * 
	 * 	@author Pan
	 */
	JsonBuilder(int size) {
		this.jsonMap = MapUtils.newHashMap(size);
	}
	
	/**	
	 * 	设置键
	 * 	
	 * 	@author Pan
	 * 	@param 	key		键
	 * 	@param 	value	值
	 * 	@return	JsonBuilder
	 */
	public JsonBuilder put(String key, Object value) {
		if (this.jsonMap == null) {
			throw new NullPointerException("缺失builder构建方法");
		}
		this.jsonMap.put(key, value);
		return this;
	}
	
	/**	
	 * 	构建
	 * 	
	 * 	@author Pan
	 * 	@return	String	
	 */
	public String build() {
		if (jsonMap == null) {
			return null;
		}
		return JsonUtils.toJson(this.jsonMap);
	}
	
	/**	
	 * 	Json是否可为空
	 * 	
	 * 	@author Pan
	 * 	@param  isNull	true为开启
	 * 	@return	JsonBuilder
	 */
	public JsonBuilder isNull(boolean isNull) {
		if (isNull) {
			IteratorUtils.values(jsonMap, (value, iterator) -> {
				if (value instanceof String) {
					if (ValidParam.isEmpty(String.valueOf(value))) {
						iterator.remove();
					}
				} else {
					if (value == null) {
						iterator.remove();
					}
				}
			});
		}
		return this;
	}
	
	/**
	 * 	{@code
	 * 	构建Map<String, Object>}格式
	 * 
	 * 	@author Pan
	 * 	@return	JsonBuilder
	 */
	public static JsonBuilder builder() {
		return JsonBuilder.builder(16);
	}
	
	/**	
	 * 	自定义Size
	 * 
	 * 	@author Pan
	 * 	@param  size	长度
	 * 	@return	JsonBuilder
	 */
	public static JsonBuilder builder(int size) {
		return new JsonBuilder(size);
	}
}
